package simorg.actions.enrollment;

import org.h2.util.StringUtils;

import simorg.domain.Course;
import simorg.domain.User;
import simorg.domain.persistence.StudentCourseJoinTable;
import simorg.domain.persistence.UserTable;
import simorg.util.PasswordHash;
import simorg.view.Flash;
import simorg.view.WebSessionContext;

public class EnrollmentJob {

	private Course course;
	private String firstName;
	private String lastName;
	private String email;
	
	
	public EnrollmentJob(Course course, String firstName, String lastName, String email) {
		this.course = course;
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
	}
	
	public void enroll(WebSessionContext wc) {
		if ( StringUtils.isNullOrEmpty(firstName) ||
				StringUtils.isNullOrEmpty(lastName) ||
				StringUtils.isNullOrEmpty(email)) {
			Flash flash = new Flash("enrollment_result");
			flash.getValues().put("error", "property missing");
			wc.addFlash(flash);
			return;
		}
		
		String username = firstName.substring(0, 1) + lastName.substring(0, Math.min(lastName.length(), 7));
		username = username.toLowerCase();
		
		boolean newUser = false;
		User user = UserTable.findByNameAndEmail(wc.getDbConnection(), firstName, lastName, email);
		if ( user == null ) {
			// make sure there are no username collisions
			int index = 1;
			boolean found;
			String baseUsername = username;
			do {
				found = (UserTable.findByUsername(wc.getDbConnection(), username) != null);
				if ( found ) {
					username = baseUsername + String.valueOf(index);
					index++;
				}
			} while (found);
		}
		if ( user == null ) {
			String password = PasswordHash.nextPassword();
			user = new User();
			user.setEmail(email);
			user.setFirstName(firstName);
			user.setLastName(lastName);
			user.setPassword(password);
			user.setUsername(username);
			UserTable.save(wc.getDbConnection(), user);
			newUser = true;
		}
		// Enroll the user.
		StudentCourseJoinTable.enroll(wc.getDbConnection(), user.getId(), course.getId());
		if ( newUser ){
			Flash flash = new Flash("enrollment_result");
			flash.getValues().put("message", (user.getFirstName() + " " + user.getLastName() + " created and enrolled"));
			wc.addFlash(flash);
			
			// send email with username and password, and enrollment
		}
		else {
			Flash flash = new Flash("enrollment_result");
			flash.getValues().put("message", (user.getFirstName() + " " + user.getLastName() + " enrolled"));
			wc.addFlash(flash);
			
			// send email with enrollment
		}
		
	}
}
